package com.quectel.core.module.scheduling.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.base.Preconditions;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.scheduling.dao.SchedulingAttendanceMonthDao;
import com.quectel.core.module.scheduling.dto.AttendanceDailyGroupMonthDto;
import com.quectel.core.module.scheduling.dto.SchedulingAttendanceMonthDto;
import com.quectel.core.module.scheduling.entity.SchedulingAttendanceMonthEntity;
import com.quectel.core.module.scheduling.service.SchedulingAttendanceMonthService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/07/27 14:51
 */
@DubboService
public class SchedulingAttendanceMonthServiceImpl implements SchedulingAttendanceMonthService{

    private static final Logger LOGGER = LoggerFactory.getLogger(SchedulingAttendanceMonthServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SCHEDULING_ATTENDANCE_MONTH_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SCHEDULING_ATTENDANCE_MONTH_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<SchedulingAttendanceMonthDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(SCHEDULING_ATTENDANCE_MONTH_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private SchedulingAttendanceMonthDao schedulingAttendanceMonthDao;
    @Autowired
    private DeptPersonService deptPersonService;
    @Autowired
    private VillageService villageService;

    /**
     * 月份分组
     *
     * @param params
     * @return
     */
    @Override
    public List<AttendanceDailyGroupMonthDto> countAttendanceGroupMonth(Map<String, Object> params) {
        return schedulingAttendanceMonthDao.countAttendanceGroupMonth(params);
    }

    @Override
    public void saveOrUpdate(SchedulingAttendanceMonthDto schedulingAttendanceMonthDto) {
        SchedulingAttendanceMonthDto oldDto = selectOne(schedulingAttendanceMonthDto.getPersonId()
                , DateUtils.format(schedulingAttendanceMonthDto.getMonth(), DateUtils.FormatType.MONTH));
        if (Objects.isNull(oldDto)) {
            DeptPersonDto deptPersonDto = deptPersonService.selectCacheById(schedulingAttendanceMonthDto.getPersonId());
            Preconditions.checkNotNull(deptPersonDto);
            schedulingAttendanceMonthDto.setMonth(DateUtil.beginOfMonth(schedulingAttendanceMonthDto.getMonth()));
            schedulingAttendanceMonthDto.setPersonName(deptPersonDto.getName());
            schedulingAttendanceMonthDto.setPersonJobNo(deptPersonDto.getJobNo());
            schedulingAttendanceMonthDto.setTenantId(deptPersonDto.getTenantId());
            schedulingAttendanceMonthDto.setVillageId(deptPersonDto.getVillageId());
            schedulingAttendanceMonthDto.setCreateTime(new Date());
            save(schedulingAttendanceMonthDto);
        } else {
            // 更新信息
            schedulingAttendanceMonthDto.setId(oldDto.getId());
            schedulingAttendanceMonthDto.setMonth(null);
            updateById(schedulingAttendanceMonthDto);
        }
    }

    @Override
    public SchedulingAttendanceMonthDto selectOne(Long personId, String monthStr) {
        SchedulingAttendanceMonthEntity schedulingAttendanceMonthEntity = schedulingAttendanceMonthDao.selectOne(new LambdaQueryWrapper<SchedulingAttendanceMonthEntity>()
                .eq(SchedulingAttendanceMonthEntity::getPersonId, personId).eq(SchedulingAttendanceMonthEntity::getMonth, monthStr + "-01"));
        SchedulingAttendanceMonthDto schedulingAttendanceMonthDto = CopyUtils.copyObj(schedulingAttendanceMonthEntity, SchedulingAttendanceMonthDto.class);
        paddingField(schedulingAttendanceMonthDto);
        return schedulingAttendanceMonthDto;
    }

    @Override
    public SchedulingAttendanceMonthDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SCHEDULING_ATTENDANCE_MONTH_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SchedulingAttendanceMonthDto selectById(Long id){
            SchedulingAttendanceMonthEntity entity = schedulingAttendanceMonthDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,SchedulingAttendanceMonthDto.class));
    }

    @Override
    public List<SchedulingAttendanceMonthDto> queryList(Map<String,Object> params){
        List<SchedulingAttendanceMonthEntity> list = schedulingAttendanceMonthDao.queryList(params);
        List<SchedulingAttendanceMonthDto> result =  CopyUtils.copyList(list,SchedulingAttendanceMonthDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<SchedulingAttendanceMonthDto> queryListWithoutPadding(Map<String,Object> params){
        List<SchedulingAttendanceMonthEntity> list = schedulingAttendanceMonthDao.queryList(params);
        return CopyUtils.copyList(list,SchedulingAttendanceMonthDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private SchedulingAttendanceMonthDto paddingField(SchedulingAttendanceMonthDto dto){
        if (dto != null){
            dto.setMonthStr(DateUtils.format(dto.getMonth(), DateUtils.FormatType.MONTH));
            DeptPersonDto deptPersonDto = deptPersonService.selectCacheById(dto.getPersonId());
            dto.setDeptPerson(deptPersonDto);

            VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
            dto.setVillage(villageDto);
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return schedulingAttendanceMonthDao.queryTotal(params);
    }

    @Override
    public Long save(SchedulingAttendanceMonthDto dto){
        SchedulingAttendanceMonthEntity entity = CopyUtils.copyObj(dto,SchedulingAttendanceMonthEntity.class);
        entity.setId(Snowflake.nextId());
        schedulingAttendanceMonthDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(SchedulingAttendanceMonthDto dto){
        SchedulingAttendanceMonthEntity entity = CopyUtils.copyObj(dto,SchedulingAttendanceMonthEntity.class);

        schedulingAttendanceMonthDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(SchedulingAttendanceMonthDto dto) {
       SchedulingAttendanceMonthEntity entity = CopyUtils.copyObj(dto,SchedulingAttendanceMonthEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, schedulingAttendanceMonthDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        schedulingAttendanceMonthDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
